#!/bin/bash

### BEGIN INIT INFO
# Provides:          ravendb-daemon
# Required-Start:    $local_fs
# Required-Stop:     $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: ravendb daemon
# Description: ravendb daemon
### END INIT INFO


printf "Recieved commnad to $1\n"


function shutRavenGracefully(){
	RDB_INST=$(ps -ef | grep corerun | grep Raven.Server.dll | wc -l)
	if [ $RDB_INST -gt 0 ]
	then
		PID=$(ps -ef | grep corerun | grep Raven.Server.dll | awk '{print $2}')
		printf "on $1 command found already running instance. killing it without resume"
		sudo /sbin/runuser RDB_USERNAME -c "echo \"lockfile\" > /tmp/ravendb.${PID}.lockfile"
		ps -ef | grep corerun | grep Raven.Server.dll | awk '{print $2}' | xargs kill
	fi
}

case "$1" in
start|restart|reload|force-reload)
	if [ "$1" == "start" ]
	then
		rm -f /tmp/ravendb.*.lockfile
	fi
	shutRavenGracefully 
	/sbin/runuser RDB_USERNAME -c 'RDB_RAVENDB_PATH/ravendb.watchdog.sh RDB_RAVENDB_PATH RDB_DOTNET_PATH' &
    ;;
stop)
	shutRavenGracefully
    ;;
esac

exit 0
